﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Negocio;
using System.Windows.Controls.Primitives;

namespace Presentacion
{
    /// <summary>
    /// Lógica de interacción para Grupos.xaml
    /// </summary>
    public partial class WGroups : UserControl
    {
      
        public static WGroups instance;        
        ObservableCollection<Player> playerAux;
        private Club club;
        private bool insertGroup;

        private WGroups()
        {
            InitializeComponent();
            listViewSelected.AddHandler(Thumb.DragDeltaEvent,
   new DragDeltaEventHandler(listViewAvailable_DragDelta),
   true);
            listViewAvailable.AddHandler(Thumb.DragDeltaEvent,
   new DragDeltaEventHandler(listViewAvailable_DragDelta),
   true);
            playerAux = new ObservableCollection<Player>();
            this.btnDelete.IsEnabled = false;
            this.Loaded += new RoutedEventHandler(Grupos_Loaded);
            club = Club.getInstance();
            insertGroup = true;
        }

        public static WGroups getInstance()
        {
            if (instance == null)
            {
                instance = new WGroups();
            }
            return instance;
        }

        void Grupos_Loaded(object sender, RoutedEventArgs e)
        {                                      
            listViewAvailable.ItemsSource = club.loadEnabledPlayers();
            cbxGroups.ItemsSource = club.Groups;
            listViewSelected.ItemsSource = playerAux;
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int pos = listViewAvailable.SelectedIndex;
                if (!playerAux.Contains(club.Players[pos]))
                {
                    playerAux.Add(club.Players[pos]);
                }
                else 
                {
                    MessageBox.Show("El jugador ya pertenece al grupo", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                listViewSelected.ItemsSource = null;
                listViewSelected.ItemsSource = playerAux;
            }
            catch (Exception)
            {
                MessageBox.Show("Error", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnEnter_Click(object sender, RoutedEventArgs e)
        {
            if (insertGroup)
            {
                Group group = club.newGroup(txbName.Text, playerAux);
                if (group != null)
                {
                    if (club.addGroup(group) == true)
                    {
                        MessageBox.Show("Grupo ingresado correctamente", "Ingreso", MessageBoxButton.OK, MessageBoxImage.Information);
                        cleanAll();
                        //playerAux.Clear();                        
                    }
                    else
                    {
                        MessageBox.Show("El Grupo ya fue ingresado al sistema", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Datos incorrectos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else 
            {
                int pos = cbxGroups.SelectedIndex;
                if (!club.groupWithSameName(txbName.Text, cbxGroups.SelectedIndex))
                {
                    club.Groups[pos] = club.updateGroup(txbName.Text, playerAux, club.Groups[pos]);
                    if (club.Groups[pos] != null)
                    {
                        cleanAll();
                        /*cbxGroups.ItemsSource = null;
                        cbxGroups.ItemsSource = club.Groups;
                        playerAux.Clear();
                        listViewSelected.ItemsSource = null;
                        listViewSelected.ItemsSource = playerAux;*/
                        MessageBox.Show("Grupo modificado correctamente", "Modificación", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageBox.Show("Datos incorrectos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Ya existe otro grupo con ese nombre.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                } 
            }            
        }

        private void cbxGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                int pos = cbxGroups.SelectedIndex;
                txbName.Text = club.Groups[pos].Name;                
                IEnumerator<Player> p = club.Groups[pos].Players.GetEnumerator();
                playerAux.Clear();
                while (p.MoveNext())
                {
                    playerAux.Add(p.Current);
                }
                listViewSelected.ItemsSource = null;
                listViewSelected.ItemsSource = playerAux;
                this.btnDelete.IsEnabled = true;
                insertGroup = false;
            }
            catch (Exception) {
                //MessageBox.Show("Error", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void txbName_GotFocus(object sender, RoutedEventArgs e)
        {
            if (txbName.Text.Length == 0) 
            {
                listViewSelected.ItemsSource = null;
                playerAux.Clear();
            }          
        }        

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int posList = listViewSelected.SelectedIndex;
                int posCombo = cbxGroups.SelectedIndex;
                playerAux.RemoveAt(posList);
                //club.Groups[posCombo].Players.RemoveAt(posList);
                listViewSelected.ItemsSource = null;
                //listViewSelected.ItemsSource = club.Groups[posCombo].Players;
                listViewSelected.ItemsSource = playerAux;
            }
            catch (Exception)
            {
                MessageBox.Show("Error", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result;
            
            result=MessageBox.Show("Esta Seguro que desea eliminar el grupo", "Atención", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (result.Equals(MessageBoxResult.OK)&& cbxGroups.SelectedIndex!=-1)
            {
                int posCombo = cbxGroups.SelectedIndex;
                club.removeGroup(posCombo);                
                playerAux.Clear();
            }
        }

        private void cleanAll() 
        {
            txbName.Text = "";
            cbxGroups.Text = "";
            listViewSelected.ItemsSource = null;
            this.btnDelete.IsEnabled = false;
            insertGroup = true;
        }

        private void btnClean_Click(object sender, RoutedEventArgs e)
        {
            cleanAll();
        }
        //Controla el tama;o de las columnas
        private void listViewAvailable_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            Thumb senderAsThumb = e.OriginalSource as Thumb;
            GridViewColumnHeader header
              = senderAsThumb.TemplatedParent as GridViewColumnHeader;
            if (header != null)
            {
                if (header.Column.ActualWidth < 240)
                {
                    header.Column.Width = 213;
                }
                if (header.Column.ActualWidth > 240)
                {
                    header.Column.Width = 213;
                }
            }

        }

        

    }
}
